package com.ruoyi.common.dto;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLOutput;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * token工具类
 */
public class JwtUtils {

    private  static final Logger log = LoggerFactory.getLogger(JwtUtils.class);

    private static final long EXPIRE_TIME = 7*24*60*60*1000;
    private static final String TOKEN_SECRET = "ywh";

    /**
     * 生成签名，7天过期
     *
     * @param **username**
     * @param **password**
     * @return
     */
    public static String sign(Long userId) {
        // 设置过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        // 加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        // 返回token字符串`
        return JWT.create().withIssuedAt(new Date()).withExpiresAt(date).withClaim("userId", userId).sign(algorithm);
    }

    /**
     * 检验token是否正确
     *
     * @param **token**
     * @return
     */
    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从token中获取登录方式信息
     *
     * @param **token**
     * @return
     */
    public static Long getUserId(String token) {
        if (!verify(token)){
            log.warn("token 不存在:{}", token);
            return null;
        }
        DecodedJWT jwt;
        try {
            jwt = JWT.decode(token);
        } catch (JWTDecodeException e) {
            e.printStackTrace();
            return null;
        }
        if (new Date().getTime() > jwt.getExpiresAt().getTime()) {
            log.warn("token 已过期:{}", token);
            return null;
        }
        return jwt.getClaim("userId").asLong();
    }

    public static void main(String[] args) {
        System.out.println(sign(1L));
    }
}
